package 连接数据库;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.UUID;

/*测试二进制的使用
* 将图片传入数据库
* 将图片出数据库传出
* */

public class hahha {
    @Test
    @DisplayName("输出数据库图片")
    public void test1() throws SQLException, IOException {
        Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","1234");
        String sql="select * from tupian where id=? ";
        var p= connection.prepareStatement(sql);
        p.setInt(1,1);
        var ok=p.executeQuery();
        if (ok.isBeforeFirst()){
            ok.next();
           // ok.getBlob(3).getBinaryStream().transferTo(new FileOutputStream(ok.getString(2)));
          String fn= UUID.randomUUID().toString()+".jpg";
          ok.getBlob(3).getBinaryStream().transferTo(new FileOutputStream(fn));

        }
    }
    @Test
    @DisplayName("利用二进制将图片传入数据库")
    public void test() throws SQLException, FileNotFoundException {
        var path="E:\\img\\yk2.jpg";
        File file = new File(path);
        String fn= file.getName().toLowerCase();
        FileInputStream is = new FileInputStream(file);
        //建立连接数据库
        Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","1234");
        var sql="insert into tupian value(1,?,?)";
        PreparedStatement p= con.prepareStatement(sql);
        p.setString(1,fn);
        p.setBlob(2,is);

        var ok=p.executeUpdate();
        if(ok>0){
            System.out.println(" 成功");
        }
    }

}
